package cn.zcib.dao;

import cn.zcib.domain.Student;

/**
 * @Author Lucky赵
 * @Date 2021年08月11日 9:14
 */
public class StudentDao implements BaseStudentDao {
    private static final Student[] students = new Student[5];//创建学生对象数组
    static {
        Student stu1 = new Student("001", "张三", 23, "1998-02-28");
        Student stu2 = new Student("002", "李四", 22, "1999-03-12");
        Student stu3 = new Student("003", "王五", 20, "2001-05-20");
        students[0]=stu1;
        students[1]=stu2;
        students[2]=stu3;
    }

    public boolean addStu(Student student) {
        //定义变量index为-1，假设数组已全部充满，没有null值
        int index = -1;
        //遍历数组取出每一个元素，判断是否为null
        for (int i = 0; i < students.length; i++) {
            Student stu = students[i];
            if (stu == null) {
                index = i;
                //如果为null，让index记录当前索引位置，使用break结束循环遍历
                break;
            }
        }
        //返回添加成功的Boolean类型状态
        if (index == -1)
            //装满了
            return false;
        else {
            //没装满，正常添加
            students[index] = student;
            return true;
        }
    }

    public Student[] findAllStu() {
        return students;
    }

    public void delStuById(String id) {
        //查找id在容器中的索引位置
        int index = getIndex(id);
        //将该索引位置使用null元素进行覆盖
        students[index]=null;
    }

    public int getIndex(String id) {
        int index=-1;
        for (int i = 0; i < students.length; i++) {
            Student stu = students[i];
            if (stu!=null&&stu.getId().equals(id)){
                index=i;
                break;
            }
        }
        return index;
    }

    public void updateStu(String id, Student student) {
        int index = getIndex(id);
        students[index]=student;
    }
}
